
#include "Simulation.h"

using namespace Pheng;

Simulation::Simulation() :
	mCollisor( Collisor() )
{}

Simulation::~Simulation()
{
	physicsBodiesMap::iterator bodiesIt;
	for (bodiesIt = mPhysicsBodies.begin(); bodiesIt != mPhysicsBodies.end(); ++bodiesIt)
		delete bodiesIt->second;
	forcesMap::iterator forcesIt;
	for (forcesIt = mGlobalForces.begin(); forcesIt != mGlobalForces.end(); ++forcesIt)
		delete[] forcesIt->second;
}

void Simulation::addGlobalForce( std::string iForceName, float* const iForce )
{
	mGlobalForces[iForceName] = iForce;
}

void Simulation::addPhysicsBody( std::string iPhysicsBodyName, PhysicsBody* iPhysicsBody )
{
	mPhysicsBodies[iPhysicsBodyName] = iPhysicsBody;
}

void Simulation::update( const float iDt )
{
	physicsBodiesMap::iterator bodiesIt, bodiesIt2;

	// Check collisions between registered entities:
	// we check each pair of entities only once, order doesn't count
	for (bodiesIt = mPhysicsBodies.begin(); bodiesIt != mPhysicsBodies.end(); ++bodiesIt)
		for (bodiesIt2 = mPhysicsBodies.begin(); bodiesIt2 != mPhysicsBodies.end(); ++bodiesIt2)
			if (bodiesIt != bodiesIt2)
				mCollisor.check(bodiesIt->second, bodiesIt2->second);

	// Apply global forces
	forcesMap::iterator forcesIt;

	for (forcesIt = mGlobalForces.begin(); forcesIt != mGlobalForces.end(); ++forcesIt)
		for (bodiesIt = mPhysicsBodies.begin(); bodiesIt != mPhysicsBodies.end(); ++bodiesIt)
			bodiesIt->second->applyForce(forcesIt->second);

	// Update all bodies
	for (bodiesIt = mPhysicsBodies.begin(); bodiesIt != mPhysicsBodies.end(); ++bodiesIt)
		bodiesIt->second->update(iDt);
}
